import mysql from "mysql";
import type {
    MysqlError,
    FieldInfo,
    Pool,
    Connection,
    PoolConfig,
} from "mysql";

export default class Handler {
    private pool: Pool;
    private connect: Connection | null = null;
    constructor(config: PoolConfig) {
        this.pool = mysql.createPool({
            ...config,
        });
    }
    public getConnection() {
        return new Promise<Connection>((resolve, reject) => {
            this.pool.getConnection((err, connection) => {
                if (err) return reject(err);
                resolve(connection);
            });
        });
    }
    public async init() {
        // @ts-ignore
        this.connect = await this.getConnection().catch((err) => {
            console.log(err);
            this.connect = null;
        });
    }
    public find(table: string, where: string, field: string[] | string) {
        if (typeof field === "string") field = [field];
        if (this.connect === null) throw new Error("not found connect");
        if (where) where = "WHERE " + where;
        return new Promise<any[]>((resolve, reject) => {
            this.connect!.query(
                `SELECT ${(field as string[]).join(
                    ",",
                )} FROM ${table} ${where}`,
                (
                    err: MysqlError | null,
                    results?: any,
                    fields?: FieldInfo[],
                ) => {
                    if (err) reject(err);
                    resolve(results);
                },
            );
        });
    }
    public end() {
        this.connect?.end((err) => {
            if (err) console.log(err);
            console.log("end successfully");
        });
    }
}

const db = new Handler({
    user: "root",
    password: "root1234",
    database: "flask_demo",
});
db.init().then(() => {
    db.find("user", "", "*").then((result) => {
        console.log(result);
    });
});
